#include <iostream>
#include <stdio.h>
#include "people.pb.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main(int argc, char **argv)
{
	int listenfd = 0;
	int connectfd = 0;
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	char buff[1024] = {0};

	memset(&server_addr, 0, sizeof(server_addr));
	memset(&client_addr, 0, sizeof(client_addr));
	server_addr.sin_port = htons(8888);
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	listenfd = socket(AF_INET, SOCK_STREAM, 0);

	int opt = 1;
	if(setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
	{
		perror("setsockopt reuseaddr error");
		return -1;
	}
	bind(listenfd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr));
	listen(listenfd, 10);

	while(1)
	{
		connectfd = accept(listenfd, NULL, NULL);
		if(connectfd < 0)
		{
			perror("accept error");
			break;
		}
		int size = read(connectfd, buff, 1023);
		buff[size] = '\0';
		std::cout<<"recv :"<<buff<<std::endl;
		std::string str = buff;
		if(str == "get people")
		{
			demo::People people;
			people.set_name("david");
			people.set_id(123);
			people.set_email("david.xx@gmail.com");
			memset(buff, 0, 1024);
			people.SerializeToArray(buff, people.ByteSize());
			write(connectfd, buff, strlen(buff));
		}
		else
		{
			write(connectfd, "Fucking client!\n", 16);
		}
		close(connectfd);
	}

	close(listenfd);
	return 0;
}
